<?php
namespace phiction;

class string_utils
{
    const INDENT_PREFIX = '    ';

    static function indent(string $str, int $level=1): string
    {
        return self::indent_by($str, self::indent_prefix($level));
    }

    static function indent_by(string $str, string $prefix): string
    {
        return self::map_line(function ($line) use ($prefix) {
            return $prefix . $line;
        }, $str);
    }

    static function map_line(callable $callback, string $str): string
    {
        return implode("\n", array_map($callback, explode("\n", $str)));
    }

    static function wrap_lines(string $str, int $width, string $prefix, string $placeholder): string
    {
        $prefix = "\n" . $prefix;
        $rest_width = $width - strlen($prefix);
        return self::map_line(function ($line) use ($width, $rest_width, $prefix, $placeholder) {
            if ($rest_width < 1) return str_repeat($placeholder, $width);
            return wordwrap($line, $rest_width, $prefix, true);
        }, $str);
    }


    static function single_lined(string $str): bool
    {
        return strpos($str, "\n") === false;
    }

    static function multi_lined(string $str): bool
    {
        return !self::single_lined($str);
    }


    static function starts_with(string $str, string $prefix): bool
    {
        $slen = strlen($str);
        $plen = strlen($prefix);
        if ($plen > $slen) return false;
        if ($plen === $slen) return $str === $prefix;
        return substr($str, 0, $plen) === $prefix;
    }


    static private function indent_prefix(int $level): string
    {
        return str_repeat(self::INDENT_PREFIX, $level);
    }
}

